# == Schema Information
#
# Table name: regions
#
#  id         :integer          not null, primary key
#  name       :string           not null
#  code       :string           not null
#  account_id :integer          not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  user_id    :integer
#

class Region < ActiveRecord::Base

	validates_uniqueness_of :user_id, message: '用户已被占用'

	belongs_to :account
	belongs_to :user
	has_many :stores
	#has_many :region_strategies


	before_create :gen_code

	def gen_code
		self.code = 'CH' << SecureRandom.hex(2)
	end

	def select_hash
		{
			id: 	id,
			name: name,
			children: stores.map(&:select_hash)
		}
	end

	def to_hash
		# TODO
		# attributes.merge(user_name: name, user_mobile: mobile)
		user ? attributes.merge(user_name: user.name, user_mobile: user.mobile) : attributes
	end
end
